// 医生列表组件


import { useEffect, useCallback } from 'react';
import { List, Image, Tag, Space, PullToRefresh, InfiniteScroll, Dropdown, Toast } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import { useAppDispatch, useAppSelector } from '../../store/hooks';
import { 
    fetchDoctors, 
    consultDoctor, 
    setCondition, 
    setSortBy, 
    resetDoctors 
} from '../../store/slices/doctorSlice';

/**
 * 医生列表组件
 * 显示医生列表，支持排序、筛选、下拉刷新和无限滚动
 * @component DoctorList
 * @returns {JSX.Element} 医生列表组件
 */
export default function DoctorList() {
    const navigate = useNavigate();
    const dispatch = useAppDispatch();
    const { 
        doctors, 
        loading, 
        hasMore, 
        page, 
        deptId, 
        condition, 
        sortBy, 
        error 
    } = useAppSelector((state) => state.doctors);

    /**
     * 加载更多医生数据
     * @function loadMore
     */
    const loadMore = useCallback(async () => {
        if (loading) return;
        await dispatch(fetchDoctors({
            deptId,
            condition,
            sortBy,
            page,
            count: 10
        }));
    }, [dispatch, deptId, condition, sortBy, page, loading]);

    // 当筛选条件改变时重新加载数据
    useEffect(() => {
        loadMore();
    }, [deptId, condition, sortBy]);

    /**
     * 处理下拉刷新
     * @function onRefresh
     */
    const onRefresh = useCallback(async () => {
        dispatch(resetDoctors());
        await loadMore();
    }, [dispatch, loadMore]);

    /**
     * 处理医生咨询点击
     * @function handleDoctorClick
     * @param {number} doctorId - 医生ID
     */
    const handleDoctorClick = useCallback(async (doctorId: number) => {
        try {
            const resultAction = await dispatch(consultDoctor(doctorId));
            if (consultDoctor.fulfilled.match(resultAction)) {
                const response = resultAction.payload;
                if (response.status === '0000') {
                    // 存储当前医生信息
                    localStorage.setItem('currentDoctor', JSON.stringify({
                        doctorId,
                        doctorUserName: response.doctorUserName
                    }));
                    // 跳转到聊天页面
                    navigate(`/inquiry/new?doctorId=${doctorId}`);
                } else {
                    Toast.show({
                        content: response.message || '咨询失败',
                        position: 'center',
                    });
                }
            }
        } catch (error) {
            if (error instanceof Error && error.message === '请先登录') {
                Toast.show({
                    content: '请先登录',
                    position: 'center',
                });
                navigate('/login');
            } else {
                Toast.show({
                    content: '咨询失败，请稍后重试',
                    position: 'center',
                });
            }
        }
    }, [dispatch, navigate]);

    // 排序选项配置
    const conditionOptions = [
        { label: '综合', value: 1 },
        { label: '好评', value: 2 },
        { label: '咨询数', value: 3 },
        { label: '价格', value: 4 }
    ];

    // 价格排序选项配置
    const sortOptions = [
        { label: '默认排序', value: undefined },
        { label: '价格从高到低', value: 1 }
    ];

    // 显示错误信息
    if (error) {
        Toast.show({
            content: error,
            position: 'center',
        });
    }

    return (
        <div style={{ padding: '12px' }}>
            {/* 排序和筛选工具栏 */}
            <Space style={{ marginBottom: '12px' }}>
                {/* 排序方式下拉菜单 */}
                <Dropdown>
                    <Dropdown.Item key="condition" title="排序方式">
                        {conditionOptions.map(option => (
                            <div
                                key={option.value}
                                onClick={() => dispatch(setCondition(option.value))}
                            >
                                {option.label}
                            </div>
                        ))}
                    </Dropdown.Item>
                </Dropdown>
                {/* 价格排序下拉菜单（仅在价格排序时显示） */}
                {condition === 4 && (
                    <Dropdown>
                        <Dropdown.Item key="sort" title="价格排序">
                            {sortOptions.map(option => (
                                <div
                                    key={option.value}
                                    onClick={() => dispatch(setSortBy(option.value))}
                                >
                                    {option.label}
                                </div>
                            ))}
                        </Dropdown.Item>
                    </Dropdown>
                )}
            </Space>

            {/* 下拉刷新容器 */}
            <PullToRefresh onRefresh={onRefresh}>
                {/* 医生列表 */}
                {doctors.length === 0 && !loading ? (
                    <div style={{ textAlign: 'center', padding: '20px', color: '#999' }}>
                        暂无医生数据
                    </div>
                ) : (
                    <List>
                        {doctors.map(doctor => (
                            <List.Item
                                key={doctor.doctorId}
                                // 医生头像
                                prefix={
                                    <Image
                                        src={doctor.imagePic}
                                        style={{ borderRadius: '50%', width: '60px', height: '60px' }}
                                        fit="cover"
                                    />
                                }
                                // 医生详细信息
                                description={
                                    <Space direction="vertical" style={{ '--gap': '4px' }}>
                                        <div>{doctor.jobTitle}</div>
                                        <div>{doctor.inauguralHospital}</div>
                                        <Space>
                                            <Tag color="primary">好评率 {doctor.praise}%</Tag>
                                            <Tag color="success">服务 {doctor.serverNum}人</Tag>
                                        </Space>
                                    </Space>
                                }
                                // 价格和评价信息
                                extra={
                                    <div style={{ textAlign: 'right' }}>
                                        <div style={{ fontSize: '16px', color: '#ff4d4f' }}>
                                            {doctor.servicePrice} H币
                                        </div>
                                        <div style={{ fontSize: '12px', color: '#999' }}>
                                            好评 {doctor.praiseNum} | 差评 {doctor.badNum}
                                        </div>
                                    </div>
                                }
                                onClick={() => handleDoctorClick(doctor.doctorId)}
                            >
                                {doctor.doctorName}
                            </List.Item>
                        ))}
                    </List>
                )}
                {/* 无限滚动加载更多 */}
                <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
            </PullToRefresh>
        </div>
    );
} 